package com.zengqingfa.datastructure.sparearray;

/**
 *
 * @fileName: SpareseArr
 * @author: zengqf3
 * @date: 2021-4-25 17:31
 * @description:
 */
public class SpareseArr {

    public static void main(String[] args) {
        //创建一个原始的二维数组
        int arr[][] = new int[11][11];
        arr[1][1] = 1;
        arr[2][2] = 1;
        arr[3][3] = 1;
        arr[4][4] = 1;
        arr[8][8] = 1;
        arr[10][7] = 1;

        //输出原始的二维数组
        System.out.println("============输出原始的二维数组========");
        for (int[] rows : arr) {
            for (int data : rows) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        //将二维数组转换为稀疏数组
        //1、先遍历二维数组，得到数组元素的个数
        int sum = 0;
        // for (int[] rows:arr){
        //     for (int data:rows){
        //         if(data !=0){
        //             sum+=1;
        //         }
        //     }
        // }
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (arr[i][j] != 0) {
                    sum += 1;
                }
            }
        }
        System.out.println("数组元素的个数：" + sum);

        //2 创建对应的稀疏数组
        //第一行需要保持数组的元数个数，有几行几列
        //3列   几行   几列   多少个值的二维数组
        int spareseArray[][] = new int[sum + 1][3];
        //给第一行赋值
        spareseArray[0][0] = 11;
        spareseArray[0][1] = 11;
        spareseArray[0][2] = sum;

        //遍历二维数组，将非0的值存放到稀疏数组中
        //定义count,记录非0元素的个数
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (arr[i][j] != 0) {
                    count++;
                    spareseArray[count][0] = i;
                    spareseArray[count][1] = j;
                    spareseArray[count][2] = arr[i][j];
                }
            }
        }

        //遍历稀疏数组
        System.out.println("==========遍历稀疏数组========");
        for (int[] rows : spareseArray) {
            for (int d : rows) {
                System.out.printf("%d\t", d);
            }
            System.out.println();
        }


        //稀疏数组还原为二维数组
        int row = spareseArray[0][0];
        int column = spareseArray[0][1];
        int num = spareseArray[0][2];
        int sourceArr[][] = new int[row][column];
        //遍历稀疏数组 从第二行开始
        for (int i = 1; i <= num; i++) {
            sourceArr[spareseArray[i][0]][spareseArray[i][1]] = spareseArray[i][2];
        }

        //遍历还原后的二维数组
        System.out.println("==========遍历还原后的二维数组========");
        for (int[] rows : sourceArr) {
            for (int d : rows) {
                System.out.printf("%d\t", d);
            }
            System.out.println();
        }
    }
}
